#!/bin/bash
set -e

# Get the IP address of this unit and the remote unit
peer_ip=$(relation-get private-address)
this_ip=$(unit-get private-address)

# Get the machine number of this unit and the remote unit. This
# takes the form '<charm name>/<index>
peer_index=$(echo $JUJU_REMOTE_UNIT | cut -d'/' -f2)
this_index=$(echo $JUJU_UNIT_NAME | cut -d'/' -f2)

# Re-create the node.json files in the data bags. Mark the new
# node as joining - the new node is the one with the higher index
if [ $this_index -gt $peer_index ]
  then
    $CHARM_DIR/lib/node_json_clustered_script --ip "$peer_ip" --index "$peer_index" --cluster
    $CHARM_DIR/lib/node_json_clustered_script --ip "$this_ip" --index "$this_index" --cluster --joining
  else
    $CHARM_DIR/lib/node_json_clustered_script --ip "$peer_ip" --index "$peer_index" --cluster --joining
    $CHARM_DIR/lib/node_json_clustered_script --ip "$this_ip" --index "$this_index" --cluster
fi

# Re-create the node.json file and re-run chef solo
$CHARM_DIR/lib/node_json_script --cluster
chef-solo -c /home/ubuntu/chef-solo/solo.rb -j /home/ubuntu/chef-solo/node.json

# Re-create the node.json with the tag. Only do this for the existing node, not the
# joining node
if [ $this_index -lt $peer_index ]
  then
  $CHARM_DIR/lib/node_json_script --cluster --tag
fi
